package ch.fhnw.qualiscan.application.controllers;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.elements.BestPracticeForm;
import ch.fhnw.qualiscan.application.elements.QuestionForm;
import ch.fhnw.qualiscan.application.models.DomainModel;
import ch.fhnw.qualiscan.application.models.QuestionModel;
import ch.fhnw.qualiscan.application.models.SurveyModel;
import ch.fhnw.qualiscan.application.views.FillOutView;
import ch.fhnw.qualiscan.core.Controller;
import ch.fhnw.qualiscan.core.db.pojos.Answer;
import ch.fhnw.qualiscan.core.db.pojos.BestPractice;
import ch.fhnw.qualiscan.core.db.pojos.Confidence;
import ch.fhnw.qualiscan.core.db.pojos.Domain;
import ch.fhnw.qualiscan.core.db.pojos.Survey;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.helpers.Permissions;
import ch.fhnw.qualiscan.core.libraries.NotificationLibrary;
import eu.livotov.tpt.i18n.TM;

@SuppressWarnings("serial")
public class FillOut extends Controller {
	
	public SurveyUserRole surveyUserRole;
	public Survey currentSurvey;
	public Domain currentDomain;
	
	public SurveyModel surveyModel;
	public DomainModel domainModel;
	public QuestionModel questionModel;
	
	public List<QuestionForm> questionFormList;
	public int newConfidenceValue = 2;
	public BestPracticeForm bpf; 
	
	
	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setView() {
		// TODO Auto-generated method stub
		view = new FillOutView(this);
		
	}

	@Override
	public void loadModels() {
		surveyModel = new SurveyModel();
		domainModel = new DomainModel();
		questionModel = new QuestionModel();
		
	}

	@Override
	public void setNeededPermissions() {
		neededPermissions.add(Permissions.LOGGEDIN);
		
	}

	@Override
	public void urlFragmentChanged(int fragmentId, String fragment) {
		
		if (fragmentId == 3) {

			int domainId;
			
			try {
				domainId = Integer.valueOf(fragment);
			} catch(NumberFormatException ex) {
				NotificationLibrary.showError(TM.get("error"), TM.get("domain.error.exists"));
				return;
			}
			
			currentDomain = domainModel.getDomainById(domainId);
			if (currentDomain == null) {
				this.getAppData().getLoaderLib().setUrlFragment(0, "Dashboard");			
			}
		}
		
		if (fragmentId == 2) {
			
			int surId = Integer.valueOf(fragment);
			surveyUserRole = surveyModel.getSurById(surId);
			if (surveyUserRole == null) {
				this.getAppData().getLoaderLib().setUrlFragment(0, "PermissionDenied");
			}
			
			currentSurvey = surveyUserRole.getSurvey();
			if(currentSurvey != null) {
				if(!surveyModel.userParticipatesSurvey(currentSurvey, this.userSessionHelper.getUser())) {
					NotificationLibrary.showError(TM.get("error"), TM.get("survey.error.usernoparticipant"));
					this.getAppData().getLoaderLib().setUrlFragment(0, "Dashboard");
					
				}
			}
			else {
				NotificationLibrary.showError(TM.get("error"), TM.get("survey.error.exists"));
				this.getAppData().getLoaderLib().setUrlFragment(0, "Dashboard");
			}
			questionFormList = new ArrayList<QuestionForm>();
			view.removeAllComponents();
			view.tabSheet.removeAllComponents();
			view.buildLayout();
			this.loadView();
		}
		
		
		
	}

	public void save() {
		// Save Answers
		for(int i = 0; i < questionFormList.size(); i++) {
			if(questionFormList.get(i).answer != 0) {
				Answer answer = questionModel.getAnswer(surveyUserRole, questionFormList.get(i).question);
				if (answer == null) {
					Answer a = new Answer();
					a.setAnswer(questionFormList.get(i).answer);
					a.setSurvey(currentSurvey);
					a.setDomain(currentDomain);
					a.setUser(userSessionHelper.getUser());
					a.setSur(surveyUserRole);
					
					questionModel.saveAnswer(a, questionFormList.get(i).question);
					
				}
				else {
					answer.setAnswer(questionFormList.get(i).answer);
					questionModel.updateAnswer(answer);
				}
			}
		}
		
		//Save Confidence
		Confidence confidence = domainModel.getConfidenceOfDomain(surveyUserRole, currentDomain);
		if (confidence == null) {
			Confidence newConfidence = new Confidence();
			newConfidence.setConfidence(newConfidenceValue);
			newConfidence.setSurvey(currentSurvey);
			newConfidence.setSur(surveyUserRole);
			newConfidence.setUser(userSessionHelper.getUser());
			
			domainModel.saveConfidenceOfDomain(newConfidence, currentDomain);
		}
		else {
			confidence.setConfidence(newConfidenceValue);
			domainModel.updateConfidenceOfDomain(confidence);
		}
		
		//Save BestPractice
		BestPractice bp = domainModel.getBestPracticeOfDomain(surveyUserRole, currentDomain);
		if (bp == null) {
			BestPractice newbp = new BestPractice();
			newbp.setBestpractice(bpf.getTextValue());
			newbp.setPublicpost(bpf.getPublicValue());
			newbp.setTitle(bpf.getTitleValue());
			newbp.setEditdate(new java.util.Date());
			newbp.setSurvey(currentSurvey);
			newbp.setUser(userSessionHelper.getUser());
			newbp.setSur(surveyUserRole);
			
			domainModel.saveBestPracticeOfDomain(newbp, currentDomain);
		}
		else {
			bp.setBestpractice(bpf.getTextValue());
			bp.setPublicpost(bpf.getPublicValue());
			bp.setTitle(bpf.getTitleValue());
			bp.setEditdate(new java.util.Date());
			domainModel.updateBestPracticeOfDomain(bp);
		}
	
		if (surveyUserRole.getRole().getId() == Config.COORDINATOR_ID) {
			this.getAppData().getLoaderLib().setUrl("EditSurvey/1/"+surveyUserRole.getId()+"");
		}
		else {
			this.getAppData().getLoaderLib().setUrl("EditSurvey/0/"+surveyUserRole.getId()+"");
		}
		
	}

}
